// pages/login/login.js
const api = require("../../config/api.js")
var app = getApp(); // 取得全局App
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {
      username: "",
      password: ""
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.stopPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad()
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //微信登录
  wxLogin: function (e) {
    wx.login({
      success: function (res) {
        console.log(res)
        //获取登录的临时凭证
        var code = res.code
        //调用后端，获取session-key
        wx.request({
          url: 'http://localhost:8080/wxLogin',
          data: {
            code: res.code
          },
          method: "POST",
          success: function (result) {
            console.log(result)
          }
        })

      }
    })
  },
  //获取用户名
  usernameInput: function (e) {
    this.setData({
      user: {
        username: e.detail.value,
        password: this.data.user.password
      }

    })


  },
  //获取密码
  passwordInput: function (e) {
    this.setData({
      user: {
        username: this.data.user.username,
        password: e.detail.value
      }
    })
  },
  //普通登录
  doLogin: function () {
    var that = this
    if (this.data.user.username.length == 0 || this.data.user.password.length == 0) {
      wx.showToast({
        title: '用户名或密码不能为空',
        icon: 'none',
        duration: 3000
      })
      return;
    }
    wx.request({
      url: api.doLogin,
      data: this.data.user,
      method: "POST",
      success: function (result) {
        if (result.statusCode == 200) {
          app.globalData.userId = result.data.userId
          app.globalData.role = result.data.role
          app.globalData.user = result.data
          console.log("success")
          console.log(app.globalData.user)
          wx.showToast({
            title: '登录成功',
          })
          wx.switchTab({
            url: '../mine/mine',
          })
        } else {
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          })
          console.log("app.globalData.user")
          console.log(app.globalData.user)
        }
      }

    })
  },
  register: function () {
    wx.navigateTo({
      url: '/pages/register/register',
    })
  }


})